package com.example.smartcity.ui.home

import android.content.Intent
import android.content.SharedPreferences.Editor
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import androidx.fragment.app.Fragment
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.bumptech.glide.Glide
import com.example.smartcity.MainActivity
import com.example.smartcity.SmartCityApplication
import com.example.smartcity.databinding.FragmentHomeBinding
import com.example.smartcity.logic.utils.Display
import com.example.smartcity.logic.utils.Toast.Companion.showToast
import com.example.smartcity.ui.AcNews.NewSFlashShowActivity
import com.example.smartcity.ui.AcNews.SeekActivity
import com.example.smartcity.ui.home.adapter.HotRecyclerViewAdapter
import com.example.smartcity.ui.home.adapter.MoreRecyclerViewAdapter
import com.example.smartcity.ui.home.fragment.*
import com.example.smartcity.ui.home.model.HotEntity
import com.example.smartcity.ui.home.model.MoreEntity
import com.example.smartcity.ui.newS.NewsViewModel
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.holder.BannerImageHolder
import com.youth.banner.indicator.CircleIndicator

class HomeFragment : Fragment() {
    /**
     *  赖加载
     */
    private val viewModel by lazy {
        ViewModelProvider(this)[HomeViewModel::class.java]
    }

    /**
     * 新闻专栏获取
     */
    private val newSViewModel by lazy {
        ViewModelProvider(this)[NewsViewModel::class.java]
    }

    private var _binding: FragmentHomeBinding? = null

    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentHomeBinding.inflate(inflater, container, false)
        val root: View = binding.root
        // 轮播图
        bannerAdapter(root, this)

        // 推荐服务
        more()

        // 热门主题
        hot()

        // 获取新闻专栏
        newS(root)

        // 搜索栏实现
        SeekNews()

        return root
    }



    /**
     * 搜索栏实现
     */
    private fun SeekNews() {

        // 实现软键盘点击事件
        binding.homeEditText.setOnEditorActionListener { _, i, _ ->
            if (i == EditorInfo.IME_ACTION_SEARCH){
                // 获取用户输入在edittext搜索框里的文件信息
                // 将内容传给另一个视图
                val intent = Intent(binding.root.context, SeekActivity::class.java)
                intent.putExtra("content", binding.homeEditText.text.toString())
                startActivity(intent)
            }
            false
        }
    }



    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }



    /**
     * TODO 主页轮播图适配器
     */
    private fun bannerAdapter(view: View, a: LifecycleOwner){
        // 存储照片集合
        val list = ArrayList<String>()

        // 发起请求
        viewModel.slideshow(mutableMapOf<String, Int>().apply {
            this["pageNum"] = 1
            this["pageSize"] = 8
            this["type"] = 2
        })

        // 获取数据
        viewModel.placeLiveData.observe(this, Observer {  resources ->
            val body = resources.getOrNull()
            if(body != null){
                viewModel.placeList.clear()
                // 添加数据
                viewModel.placeList.addAll(body)
            }

            // 取出数据照片地址添加到集合
            for (i in viewModel.placeList) {
                if (list.size < viewModel.placeList.size) {
                    list.add(SmartCityApplication.url + i.advImg)
                }
            }

            // 轮播图适配器
            binding.banner.setBannerRound(35F)
            binding.banner.setAdapter(object : BannerImageAdapter<String>(list){
                override fun onBindView(
                    holder: BannerImageHolder?,
                    data: String?,
                    position: Int,
                    size: Int
                ) {
                    data?.let {
                        holder?.let {
                            Glide.with(view)
                                .load(data)
                                .into(holder.imageView)
                        }
                    }
                }
            }).addBannerLifecycleObserver(a).indicator = CircleIndicator(context)

            binding.banner.setOnBannerListener { data, position ->
                val intent = Intent(context, NewSFlashShowActivity::class.java)
                intent.putExtra("model", position.toString())
                startActivity(intent)
            }
        })

        // 显示轮播图
        binding.homeBanner.visibility = View.VISIBLE
    }



    /**
     * TODO 主页推荐服务
     */
    private fun more(){

        // 存储标题和照片地址
        val array = ArrayList<MoreEntity>()


        // recyclerview适配器
        val layout = GridLayoutManager(context, 5)
        binding.homeRecyclerView.layoutManager = layout

        // 设置适配器
        val adapter = MoreRecyclerViewAdapter(this, array)
        binding.homeRecyclerView.adapter = adapter

        binding.homeRecyclerView.isNestedScrollingEnabled = false

        viewModel.more("N")

        // 从viewModel获取数据
        viewModel.moreLiveData.observe(this, Observer { resources ->
            val body = resources.getOrNull()
            if (body != null) {
                // 先清空
                viewModel.moreList.clear()
                // 添加
                viewModel.moreList.addAll(body)
            }

            // 添加数据
            for (i in viewModel.moreList){
                val size = viewModel.moreList.size
                if(array.size <= size){
                    array.add(MoreEntity(SmartCityApplication.url + i.imgUrl,i.serviceName))
                    adapter.notifyItemChanged(array.size)
                }else break
            }

            array.add(MoreEntity("", "全部服务"))
        })

        // 显示推荐服务
        binding.homeMore.visibility = View.VISIBLE
    }


    /**
     * TODO 热门主题
     */
    private fun hot(){
        // 存储热门主题
        val array = ArrayList<HotEntity>()

        // 适配器设置
        val layoutManager = LinearLayoutManager(context)
        binding.homeNewsRecyclerView.layoutManager = layoutManager
        // 水平设置
        layoutManager.orientation = LinearLayoutManager.HORIZONTAL

        val adapter = HotRecyclerViewAdapter(binding.root, array)
        binding.homeNewsRecyclerView.adapter = adapter

        viewModel.hot("Y")
        viewModel.hotLiveData.observe(this, Observer { resources ->
            val place = resources.getOrNull()
            if (place != null){
                // 先清空
                viewModel.hotList.clear()
                // 将数据添加到viewModel里面的集合中
                viewModel.hotList.addAll(place)
            }

            // 读取数据存到集合
            for (i in viewModel.hotList){
                if (array.size < viewModel.hotList.size){
                    // 将图片地址和服务器拼接， 第二个参数是标题内容
                    array.add(HotEntity(SmartCityApplication.url + i.cover, i.title))
                    // 每循环一次刷新适配器
                    adapter.notifyItemChanged(array.size)
                }
            }
        })
        // 显示布局
        binding.homeHot.visibility = View.VISIBLE
    }


    /**
     * TODO 获取新闻专栏
     */
    private fun newS(view: View){
        // 获取新闻专栏
        val tab = binding.homeTabLayout
        val vp = binding.homeViewPager2

        tab.tabMode = TabLayout.MODE_SCROLLABLE

        vp.adapter = object : FragmentStateAdapter(this){
            override fun getItemCount() = 6

            override fun createFragment(position: Int): Fragment = when(position){
                0 -> fragment1()
                1 -> fragment2()
                2 -> fragment3()
                3 -> fragment4()
                4 -> fragment5()
                else -> fragment6()
            }


        }

        TabLayoutMediator(tab, vp){tab, position ->
            when(position){
                0 -> tab.text = SmartCityApplication.title1
                1 -> tab.text = SmartCityApplication.title2
                2 -> tab.text = SmartCityApplication.title3
                3 -> tab.text = SmartCityApplication.title4
                4 -> tab.text = SmartCityApplication.title5
                else -> tab.text = SmartCityApplication.title6
            }
        }.attach()

        // 获取屏幕像素转换成dp
        // 然后将LinearLayout设置对比屏幕高度
        val sizeHeight = Display.getHeight(activity!!)
        val float = context?.resources?.displayMetrics?.density
        val size = (sizeHeight.toInt() / 1.1 - 50F).toInt()
        binding.hotNews.layoutParams.height = size

        // 将界面显示出来
        binding.hotNews.visibility = View.VISIBLE
    }
}